package cloudspace.vm.io.console;

import java.util.concurrent.ScheduledFuture;

import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Executions;

import cloudspace.vm.VM;


public abstract class CometEvent implements Runnable
{
    protected VM vmContext;

    protected Desktop desktopContext;

    private ScheduledFuture<CometEvent> handler;

    protected Logger logger = Logger.getLogger( CometEvent.class );


    protected void prepare() throws InterruptedException
    {
        vmContext.enter();
    }


    public CometEvent()
    {
        logger.debug( "Comet Event Handler is starting" );
        vmContext = VM.currentVM();
        desktopContext = Executions.getCurrent().getDesktop();
    }


    public VM getVM()
    {
        return vmContext;
    }


    protected void cleanup()
    {
        // Executions.deactivate(desktopContext);
        VM.leave();
    }


    public void giveHandle( ScheduledFuture<CometEvent> handle )
    {
        handler = handle;
    }


    public void halt()
    {
        String desktopID = "unknown";
        if ( desktopContext != null && desktopContext.getId() != null )
        {
            desktopID = desktopContext.getId();
        }
        logger.info( "Halting Comet thread attached to " + desktopID );
        handler.cancel( true );
    }
}
